package com.cmc.cloud.cmclink.doc.mq;

import com.alibaba.fastjson.JSON;
import com.cmc.cloud.cmclink.doc.api.document.emums.SoStatusEnum;
import com.cmc.cloud.cmclink.doc.convert.*;
import com.cmc.cloud.cmclink.doc.entity.SoDO;
import com.cmc.cloud.cmclink.doc.service.so.*;
import com.cmc.cloud.cmclink.doc.vo.sovo.socargovo.SoCargoUpdateReqVO;
import com.cmc.cloud.cmclink.doc.vo.sovo.socontactvo.SoContactUpdateReqVO;
import com.cmc.cloud.cmclink.doc.vo.sovo.soforecastvo.SoForecastUpdateReqVO;
import com.cmc.cloud.cmclink.doc.vo.sovo.soscnvo.SoScnUpdateReqVO;
import com.cmc.cloud.cmclink.doc.vo.sovo.sovo.SoCreateAndUpdateReqVo;
import com.cmc.cloud.cmclink.doc.vo.sovo.sovo.SoQueryReqVO;
import com.cmc.cloud.cmclink.doc.vo.sovo.sovo.SoUpdateReqVO;
import com.cmc.cloud.cmclink.doc.vo.sovo.sovslvoyvo.SoVslvoyUpdateReqVO;
import com.cmes.framework.security.core.LoginUser;
import com.cmes.framework.security.core.util.SecurityFrameworkUtils;
import com.cmes.framework.tenant.core.context.TenantContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * 消费者
 *
 * @author huzheng
 * @date 2025/09/16 13:36
 **/
@Slf4j
@Component
@RocketMQMessageListener(consumerGroup = "rocketmq_so_create_consumer_group",
        //topic = "${rocketmq.consumer.topic}",
        topic = "topic-edi-so-import", maxReconsumeTimes = 3)
public class SoEdiConsumer implements RocketMQListener<SoEdiReqVO> {

    private static final String FUNCODE_SO_CREATE = "9";
    private static final String FUNCODE_SO_UPDATE = "4";
    private static final String FUNCODE_SO_DELETE = "3";
    private static final String SO_EDI_CREATOR = "9876543212345";
    private static final String SO_EDI_REQUEST_SUCCESS = "200";
    private static final String SO_EDI_REQUEST_FAIL = "500";


    @Resource
    private BizSoService bizSoService;
    @Resource
    private SoService soService;
    @Resource
    private SoVslvoyService soVslvoyService;
    @Resource
    private SoCargoService soCargoService;
    @Resource
    private SoForecastService soForecastService;
    @Resource
    private SoContactService soContactService;
    @Resource
    private SoScnService soScnService;
    @Autowired
    private MyProducer myProducer;

    @Override
    public void onMessage(SoEdiReqVO message) {
        log.info("topic-edi-so-import-getMessage:{}", JSON.toJSONString(message));
        LoginUser originLoginUser = new LoginUser();
        originLoginUser.setId(Long.parseLong(SO_EDI_CREATOR));
        TenantContextHolder.setTenantId(172L);
        SecurityFrameworkUtils.setNoneHttpLoginUser(originLoginUser);
        String blNo = message.getData().getBlNo();
        String bookingNo = message.getData().getBookingNo();
        if (StringUtils.isEmpty(blNo) && StringUtils.isEmpty(bookingNo)) {
            return;
        }
        List<String> msgList = new ArrayList<>();
        HashMap<String, Object> messageResp = new HashMap<>(8);
        messageResp.put("code", SO_EDI_REQUEST_SUCCESS);
        messageResp.put("msgId", message.getMsgId());
        String funCode = message.getFuncCode();
        List<String> ediBiz = Arrays.asList(FUNCODE_SO_CREATE, FUNCODE_SO_UPDATE, FUNCODE_SO_DELETE);
        if (!ediBiz.contains(funCode)) {
            msgList.add("不在业务受理范围的funcCode:" + funCode);
            messageResp.put("msgList", msgList);
            messageResp.put("code", SO_EDI_REQUEST_FAIL);
            myProducer.sendMessage("edi-import-response", messageResp);
            return;
        }

        if (FUNCODE_SO_DELETE.equals(funCode)) {
            try {
                SoQueryReqVO req = new SoQueryReqVO();
                req.setBookingNo(bookingNo);
                req.setBlNo(blNo);
                SoDO soDo = soService.getSoDoByBookingNoOrBlNo(req);
                if (null != soDo) {
                    bizSoService.batchDeleteDraft(Collections.singletonList(soDo.getId()), SO_EDI_CREATOR);
                    msgList.add("订舱信息删除成功，订舱号：" + bookingNo + "，soId:" + soDo.getId());
                }
            } catch (Exception e) {
                msgList.add(e.getMessage());
                messageResp.put("code", SO_EDI_REQUEST_FAIL);
            }
            messageResp.put("msgList", msgList);
            myProducer.sendMessage("edi-import-response", messageResp);
            return;
        }
        //构建创建SO方法
        SoCreateAndUpdateReqVo createReqVO = new SoCreateAndUpdateReqVo();
        SoUpdateReqVO soUpdateReqVO = SoConvert.INSTANCE.convetSoUpdateReqDto(message.getData());
        createReqVO.setSo(soUpdateReqVO);
        //收发通信息
        SoScnUpdateReqVO soScnUpdateReqVO = SoScnConvert.INSTANCE.convertSoScnUpdateReqDto(message.getData().getScnList().get(0));
        createReqVO.setSoScn(soScnUpdateReqVO);
        //船名航次信息
        List<SoVslvoyUpdateReqVO> soVslvoyList = SoVslvoyConvert.INSTANCE.ediConvertSoVslvoyUpdateReqDto(message.getData().getVslvoyList());
        createReqVO.setSoVslvoyList(soVslvoyList);
        //预配箱信息
        List<SoForecastUpdateReqVO> soForecastList = SoForecastConvert.INSTANCE.ediConvertSoForecastUpdateReqDto(message.getData().getForecastList());
        createReqVO.setSoForecastList(soForecastList);
        //货物信息
        List<SoCargoUpdateReqVO> soCargoList = SoCargoConvert.INSTANCE.ediConvertSoCargoUpdateReqDto(message.getData().getCargoList());
        createReqVO.setSoCargoList(soCargoList);
        //订舱联系人信息
        List<SoContactUpdateReqVO> soContactList = SoContactConvert.INSTANCE.ediConvertSoContactUpdateReqDto(message.getData().getContactList());
        createReqVO.setSoContactList(soContactList);
        Long soId = null;
        try {
            if (FUNCODE_SO_CREATE.equals(funCode)) {
                SoQueryReqVO req = new SoQueryReqVO();
                req.setBookingNo(bookingNo);
                SoDO soDo = soService.ediGetByBookingNoOrBlNo(req);
                if (null != soDo) {
                    msgList.add("要创建的订舱信息已存在，如需更新请走更新流程，订舱号：" + bookingNo + "，soId:" + soDo.getId());
                    messageResp.put("msgList", msgList);
                    messageResp.put("code", SO_EDI_REQUEST_FAIL);
                    myProducer.sendMessage("edi-import-response", messageResp);
                    return;
                }
                soId = bizSoService.createOrUpdateSo(createReqVO, false, SO_EDI_CREATOR);
                soDo = soService.getSo(soId);
                soDo.setBlNo(blNo);
                soDo.setBookingNo(bookingNo);
                soService.updateById(soDo);
                bizSoService.batchSubmitDraft(Collections.singletonList(soId), SO_EDI_CREATOR);
                msgList.add("订舱信息创建成功，订舱号：" + bookingNo + "，soId:" + soId);
                if (!message.getNeedApproval()) {
                    soDo.setSoStatus(SoStatusEnum.BookingConfirmed.getValue());
                    soService.updateById(soDo);
                }
            }
            if (FUNCODE_SO_UPDATE.equals(funCode)) {
                SoQueryReqVO req = new SoQueryReqVO();
                req.setBookingNo(message.getData().getBookingNo());
                req.setBlNo(message.getData().getBlNo());
                SoDO soDo = soService.ediGetByBookingNoOrBlNo(req);
                if (null != soDo) {
                    String soStatus = soDo.getSoStatus();
                    if (!SoStatusEnum.BookingDraft.getValue().equals(soStatus)) {
                        msgList.add("订舱信息不是草稿状态无法修改：" + bookingNo);
                        messageResp.put("msgList", msgList);
                        messageResp.put("code", SO_EDI_REQUEST_FAIL);
                        myProducer.sendMessage("edi-import-response", messageResp);
                        return;
                    }
                    soUpdateReqVO.setId(soDo.getId());
                    deleteSoRelations(Collections.singletonList(soDo.getId()));
                    bizSoService.createOrUpdateSo(createReqVO, true, SO_EDI_CREATOR);
                    bizSoService.batchSubmitDraft(Collections.singletonList(soDo.getId()), SO_EDI_CREATOR);
                    if (!message.getNeedApproval()) {
                        soDo.setSoStatus(SoStatusEnum.BookingConfirmed.getValue());
                        soService.updateById(soDo);
                    }
                    msgList.add("订舱信息更新成功，订舱号：" + bookingNo + "，soId:" + soId);
                } else {
                    msgList.add("订舱信息不存在，订舱号：" + bookingNo);
                }
            }
        } catch (Exception e) {
            msgList.add(e.getMessage());
            messageResp.put("code", SO_EDI_REQUEST_FAIL);
        }
        messageResp.put("msgList", msgList);
        myProducer.sendMessage("edi-import-response", messageResp);
    }

    public void deleteSoRelations(List<Long> ids) {
        soVslvoyService.deleteBySoIds(ids);
        soCargoService.deleteBySoIds(ids);
        soForecastService.deleteBySoIds(ids);
        soContactService.deleteBySoIds(ids);
        soScnService.deleteBySoIds(ids);

    }
}
